package com.kingtone.rongji.fragment;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.MainActivity;
import com.kingtone.rongji.ProductDetailActivity;
import com.kingtone.rongji.R;
import com.kingtone.rongji.biz.Product;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.AppRestClient;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class MyFavoriteFragment extends BaseFragment {

	private TextView title = null;
	private ImageView backBtn = null;
	private ImageView leftIcon = null;
	private TextView rightTitle = null;
	private ListView addressList = null;
	private MainActivity mActivity;
	private MyFavoriteAdapter favoriteAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mActivity = (MainActivity) this.getActivity();
		super.onCreate(savedInstanceState);
		getFavoriteList();
	}
	
	public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
		View localView = paramLayoutInflater.inflate(R.layout.fragment_my_favorite, paramViewGroup, false);
		setupView(localView);
		return localView;
	}
	
	private void setupView(View paramView)
	{
		title = (TextView)paramView.findViewById(R.id.title);
		title.setText(getString(R.string.my_favorite));
		backBtn = (ImageView)paramView.findViewById(R.id.back);
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				getActivity().onBackPressed();
			}
		});
		
		leftIcon = (ImageView)paramView.findViewById(R.id.left_icon);
		leftIcon.setBackgroundResource(R.drawable.icon_cang);
		
		rightTitle = (TextView)paramView.findViewById(R.id.right_title);
		rightTitle.setText(getString(R.string.my_favorite));
		
		addressList = (ListView)paramView.findViewById(R.id.my_favorite_list);
		//点击打开产品详情
		addressList.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				
			}
		});
	}
	
	/**
	 * 获取我的收藏列表
	 */
	public void getFavoriteList()
	{
		String userId = SharedPreferencesUtil.getInstance(mActivity).getString(AppContasts.USERID_KEY);
		RongJiRestClient.getFavoriteList(userId, 0, 1000,new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(getActivity());
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
			    if(arg2 != null)
			    {
			    	String filureStr = new String(arg2);
					Log.d("failure", filureStr);
			    }
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					JSONObject obj = null;
					ArrayList<Product> list = new ArrayList<Product>();
					try {
						obj = new JSONObject(result);
						if(obj.has("Data"))
						{
							JSONArray pArray = obj.getJSONArray("Data");
							Gson gson = new Gson();
							JsonParser parser = new JsonParser();
							JsonElement element = parser.parse(pArray.toString());
							if(element instanceof JsonArray)
							{
								JsonArray array = element.getAsJsonArray();
								for(JsonElement myFav:array) {
									Product object = gson.fromJson(myFav, Product.class);
									list.add(object);
								}
							}
						}
					} catch (JSONException e) {

						e.printStackTrace();
					}
					favoriteAdapter = new MyFavoriteAdapter(mActivity, list);
					addressList.setAdapter(favoriteAdapter);	
				}
			}	
		});
	}
	
	/**
	 * 删除收藏
	 * @param productId
	 */
	private void delFavorite(String productId)
	{
		String userId = SharedPreferencesUtil.getInstance(mActivity).getString(AppContasts.USERID_KEY);
		RongJiRestClient.delFavorite(userId, productId, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(mActivity);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
			    if(arg2 != null)
			    {
			    	String filureStr = new String(arg2);
					Log.d("failure", filureStr);
			    }
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				
				RongJiUtils.dismissProgress();
				//删除收藏成功后，重新查询更新列表
				getFavoriteList();
			}	
		});
	}
	
	class MyFavoriteAdapter extends BaseAdapter
	{
		private Context context = null;
		private ArrayList<Product> favList = null;
		private LayoutInflater inflater; 
	    private Product fav = null;
		public MyFavoriteAdapter(Context context, ArrayList<Product> addList)
		{
			this.inflater=LayoutInflater.from(context);
			this.context = context;
			this.favList = addList;
		}
		@Override
		public int getCount()
		{
			return favList.size();
		}

		@Override
		public Object getItem(int position)
		{
			return favList.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View view;
			ViewHolder holder = null;
			fav = favList.get(position);
			//如果已加载过，使用缓存技术不再重新加载
			if(convertView!=null){
				view=convertView;
				holder=(ViewHolder) view.getTag();
			}else{
				view=inflater.inflate(R.layout.my_favorite_item, null);
				holder = new ViewHolder();
				holder.favProductIcon = (ImageView)view.findViewById(R.id.fav_product_icon);
				holder.favProductName = (TextView) view.findViewById(R.id.fav_product_name);
				holder.favNoticePrice =(TextView) view.findViewById(R.id.fav_notice_price);
				holder.favCurrentPrice =(TextView) view.findViewById(R.id.fav_current_price);
				holder.favStore =(TextView) view.findViewById(R.id.fav_stock);
				holder.favNoticeDate =(TextView) view.findViewById(R.id.fav_notice_date);
				holder.favDel = (ImageView)view.findViewById(R.id.my_favorite_delete);
			}
			holder.favDel.setTag(position);
			holder.favDel.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					if(v instanceof ImageView)
					{
						int index = (Integer) v.getTag();
						delFavorite(favList.get(index).getProductId());
					}	
				}
			});
			final String productId = favList.get(position).getProductId();
			holder.favProductIcon.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					gotoDetailProduct(productId);	
				}
			});
			
			holder.favProductName.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					gotoDetailProduct(productId);	
				}
			});
			
			view.setTag(holder);
			ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context));
			String productIcon = AppRestClient.convertImageUrl(fav.getProductId(), fav.getImageName());
			if(!TextUtils.isEmpty(productIcon))
			{
				ImageLoader.getInstance().displayImage(productIcon, holder.favProductIcon);
			}
			holder.favProductName.setText(fav.getProductName());
			holder.favNoticePrice.setText(context.getString(R.string.notice_price) + fav.getUnitPrice());
			holder.favCurrentPrice.setText(context.getString(R.string.current_price)+ fav.getMarketPrice());
			holder.favStore.setText(context.getString(R.string.store)+ fav.getTotalInventory());
			holder.favNoticeDate.setText(context.getString(R.string.notice_date) + RongJiUtils.revertDate(fav.getInDate()));
			
			return view;
		}
		
		private class ViewHolder
		{
			public ImageView favProductIcon;
			public TextView favProductName;
			public TextView favNoticePrice;
			public TextView favCurrentPrice;
			public TextView favStore;
			public TextView favNoticeDate;
			public ImageView favDel;
		}
		
		private void gotoDetailProduct(String productId) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(mActivity, ProductDetailActivity.class);
			Bundle ext = new Bundle();
			ext.putString("productId", productId);
			intent.putExtras(ext);
			mActivity.startActivity(intent);
		}
	}
}
